package com.thread.book.book2;

import org.junit.Test;

import java.util.concurrent.*;

// RecursiveTask: 有返回值的实现类
public class ForkJoinTest extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 200000; //切分的子任务阈值
    private int start;
    private int end;

    public ForkJoinTest(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if (end - start < THRESHOLD) { //如果任务很小,不需要分直接计算
            for (int i = start; i <= end; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum += i;
            }
        } else {  //分开成子任务分别计算
            int middle = (end + start) / 2;
            ForkJoinTest one = new ForkJoinTest(start, middle);
            ForkJoinTest two = new ForkJoinTest(middle + 1, end);
            one.fork();
            two.fork();
            //等待子任务完成
            sum = one.join() + two.join();
        }
        return sum;
    }

    public static void main(String[] args) {
        //必须由ForkJoinPool执行
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //提交,返回一个包装类
        long start = System.currentTimeMillis();
        ForkJoinTask<Integer> result = forkJoinPool.submit(new ForkJoinTest(1, 4));
        try {
            System.out.println(result.get());//获取结果,没计算完会阻塞
            long end = System.currentTimeMillis();
            System.out.println(end - start);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
